<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <!-- required modeler styles -->
    <link rel="stylesheet" href="../lib/bpm/assets/diagram-js.css"/>
    <link rel="stylesheet" href="../lib/bpm/assets/bpmn-font/css/bpmn.css"/>
    <link rel="stylesheet" href="fields.css">

    <!-- modeler distro -->
    <script src="../lib/bpm/bpmn-modeler.development.js" type="text/javascript"></script>

    <!-- needed for this example only -->
    <script src="../lib/jquery/jquery.js"></script>

    <script src="../lib/artTemplate/template-web.js"></script>

    <link rel="stylesheet" href="../lib/bootstrap-table/bootstrap-table.min.css">
    <script src="../lib/bootstrap-table/bootstrap-table.min.js"></script>
    <script src="../lib/bootstrap-table/locale/bootstrap-table-zh-CN.js"></script>

    <!-- example styles -->
    <style>
        html, body {
            height: 100%!important;
            padding: 0;
            margin: 0;
        }
        #canvas{
            padding: 0;
            margin: 0;
            height: 1000px;
        }
        .diagram-note {
            background-color: rgba(66, 180, 21, 0.7);
            color: White;
            border-radius: 5px;
            font-family: Arial;
            font-size: 12px;
            padding: 5px;
            min-height: 16px;
            width: 50px;
            text-align: center;
        }
        .needs-discussion:not(.djs-connection) .djs-visual > :nth-child(1) {
            stroke: rgba(66, 180, 21, 0.7) !important; /* color elements as red */
        }
        #action {
            position: fixed;
            bottom: 20px;
            left: 20px;
        }
    </style>
    <script src="fields.js"></script>
    <script src="../lib/menu/jquery.contextMenu.min.js"></script>
    <script src="../lib/menu/jquery.ui.position.min.js"></script>
    <link rel="stylesheet" href="../lib/css/style.css">
    <link rel="stylesheet" href="../lib/menu/jquery.contextMenu.min.css">
    <link rel="stylesheet" href="../lib/font/css/font-awesome.min.css">
    <script src="../lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <script src="../lib/layer/layer.js"></script>
    <script src="../lib/vue/vue.js"></script>
    <script src="../lib/vue/vue-util.js"></script>

    <style>
        .fixstyle{
            padding: 10px;
        }
        .fixstyle h5{
            font-weight: bold;
        }
        .fixstyle label{
            margin-right: 10px;
            font-weight: normal;
        }
        .fixstyle input[type=radio]{
            margin-right: 5px;
        }
    </style>
</head>
<body>

<div id="content">
    <div class="bs-example bs-example-tabs" data-example-id="togglable-tabs">
        <ul id="myTabs" class="nav nav-tabs" role="tablist">
            <li role="presentation" ><a href="#tab1" id="tab1-tab" role="tab" data-toggle="tab" aria-controls="baseInfo" aria-expanded="true">表单</a></li>
            <li role="presentation" ><a href="#tab2" role="tab" id="tab2-tab" data-toggle="tab" aria-controls="">流程</a></li>
            <li role="presentation" ><a href="#tab3" id="tab3-tab" role="tab" data-toggle="tab" aria-controls="taskProduceRule" aria-expanded="true">表单字段</a></li>
            <li role="presentation" ><a href="#tab4" id="tab4-tab" role="tab" data-toggle="tab" aria-controls="funcSet" aria-expanded="true">权限设置</a></li>
            <li role="presentation" ><a href="#tab6" id="tab6-tab" role="tab" data-toggle="tab" aria-controls="trigger" aria-expanded="true">触发器</a></li>
            <li role="presentation" ><a href="#tab5" id="tab5-tab" role="tab" data-toggle="tab" aria-controls="elseSetting" aria-expanded="true">其它设置</a></li>

        </ul>
        <div id="myTabContent" class="tab-content">
            <div class="tab-pane fade" id="tab1" aria-labelledby="tab1-tab">
                <form name="form-search" class="form-horizontal tab1" novalidate="novalidate">
                    <div class="row panel-form-input-group">

                        <div class="col-xs-12 form-group " data-show="" style="margin-top: 20px;">
                            <label class="col-xs-3 text-right">
                                <span style="color:red">*</span>
                                分类
                            </label>
                            <div id="catId" class="col-xs-8" style="padding-right: 15px;padding-left: 15px; max-width:400px">
                            </div>
                        </div>

                        <div class="col-xs-12 form-group " data-show="">
                            <label class="col-xs-3 text-right">
                                <span style="color:red">*</span>
                                表单
                            </label>
                            <div id="formId" class="col-xs-8" style="padding-right: 15px;padding-left: 15px; max-width:400px">
                            </div>
                        </div>

                        <div class="col-xs-12 form-group " data-show="">
                            <label for="modelName" class="col-xs-3 text-right">
                                <span style="color:red">*</span>

                                工作流名称
                            </label>
                            <div class="col-xs-8" style="padding-right: 15px;
                        padding-left: 15px; max-width:400px">
                                <input type="text" class="form-control input-sm" id="modelName" name="modelName">

                            </div>
                        </div>

                        <div class="col-xs-12 form-group " data-show="">
                            <label for="desc" class="col-xs-3 text-right">
                                流程说明
                            </label>
                            <div class="col-xs-8" style="padding-right: 15px;
                        padding-left: 15px; max-width:400px">
                                <textarea type="text" class="form-control input-sm" rows="5" id="desc"></textarea>

                            </div>
                        </div>

                        <!--<div class="col-xs-12 form-group " data-show="">-->
                            <!--<label for="permSet" class="col-xs-3 text-right">-->
                                <!--权限设置-->
                            <!--</label>-->
                            <!--<div class="col-xs-8" style="padding-right: 15px;-->
                        <!--padding-left: 15px; max-width:400px">-->
                                <!--<textarea readonly name="" id="permSet" cols="50" rows="4"></textarea>-->
                                <!--<span>-->
                                    <!--<a href="javascript:;" class="btn btn-sm" id="setRole" >设置</a>-->
                                    <!--<a href="javascript:;" class="btn btn-sm" id="cleanRole">清空</a>-->
                                <!--</span>-->

                            <!--</div>-->
                        <!--</div>-->



                    </div>
                    <div class="col-xs-12 text-center" style="padding:20px 0;display: none">
                        <button type="button" href="javascript:;" class="btn btn-info" id="nextStep" style="margin-right: 10px;">
                            下一步
                        </button>

                    </div>
                </form>
            </div>
            <div class="tab-pane fade" id="tab2" aria-labelledby="tab2-tab">
                <!--<div class="panel-body">-->
                    <div id="canvas" class="tab2"></div>
                    <!--<button id="save-button" class="btn btn-info tab2">保存</button>-->
                <!--</div>-->
            </div>

            <div class="tab-pane fade" id="tab3" aria-labelledby="tab3-tab">
            </div>
            <div class="tab-pane fade" id="tab4" aria-labelledby="tab4-tab">
                <div class="row panel-form-input-group">

                    <div class="col-xs-12 form-group " data-show="">
                        <div id="dataList" style="padding: 10px;">
                            <table class="table table-striped table-bordered">
                                <tr>
                                    <th>角色名</th>
                                    <th>权限详情</th>
                                </tr>
                                <tr v-for="v in roles">
                                    <td>{{v.text}}</td>
                                    <td>
                                        <label>
                                            <input type="checkbox" v-model="v.ps" value="sync">
                                            同步
                                        </label>
                                        <label>
                                            <input type="checkbox" v-model="v.ps" value="edit">
                                            编辑
                                        </label>
                                        <label>
                                            <input type="checkbox" v-model="v.ps" value="pause">
                                            暂停
                                        </label>
                                        <label>
                                            <input type="checkbox" v-model="v.ps" value="resume">
                                            恢复（暂停）
                                        </label>
                                        <label>
                                            <input type="checkbox" v-model="v.ps" value="forceEnd">
                                            强制结束
                                        </label>
                                        <label>
                                            <input type="checkbox" v-model="v.ps" value="forceResume">
                                            恢复（强制结束）
                                        </label>
                                        <label >
                                            <input type="checkbox" v-model="v.ps" value="urge">
                                            催办
                                        </label>
                                        <label>
                                            <input type="checkbox" v-model="v.ps" value="del">
                                            删除
                                        </label>
                                        <label>
                                            <input type="checkbox" v-model="v.ps" value="comment">
                                            批注
                                        </label>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="tab6" aria-labelledby="tab6-tab">
                <trigger-edit :data="data"></trigger-edit>
            </div>
            <div class="tab-pane fade fixstyle" id="tab5" aria-labelledby="tab5-tab">
                <h5>批注时提醒经办人</h5>
                <label >
                    <input type="radio" name="noticeOnComment" v-model="data.noticeOnComment" value="y">是
                </label>
                <label >
                    <input type="radio" name="noticeOnComment" v-model="data.noticeOnComment" value="n">否
                </label>
            </div>

            <script>
            </script>
            <div id="action">
                <button id="save-button" class="btn btn-info tab2">保存</button>
                <button id="check-button" class="btn btn-success tab2" style="margin-left: 10px; display: none">检查</button>
            </div>

        </div>
    </div>
</div>

<div id="app" style="display: none">
    <node-edit ref="edit"></node-edit>
</div>

<script type="text/html" id="model_temp">
    <select class="form-control input-sm" id="selectForm">
        {{each formList value index}}
        <optgroup label="{{value.name}}">
            {{each value.children v i}}
            <option value="{{v._id}}">{{v.name}}</option>
            {{/each}}
        </optgroup>
            <!--<input type="text" class="" value="{{value.title}}">-->
        {{/each}}
    </select>
</script>
<script type="text/html" id="cat_temp">
    <select class="form-control input-sm" id="selectCat">
        {{each catList value index}}
        <option value="{{value.id}}">{{value.name}}</option>
        {{/each}}
    </select>
</script>
<script>
    loadComponent("node-edit", "./node.edit.component.html");
    loadComponent("trigger-edit", "./trigger.comp.html");

    var app = new Vue({
        el:"#app"
    });
    var tab5 = new Vue({
        el: "#tab5",
        data: {
            data:{
                noticeOnComment: 'n'
            }
        }
    });
    var tab6 = new Vue({
        el: "#tab6",
        data:{
            data:{

            }
        }
    });

    function getNodeEmptyData(){
         return JSON.parse(JSON.stringify(app.$refs.edit.$data));
    }

</script>

<script>
    window.form = null;
    window.fields = [];
    // 用于配置页面赋值传值
    window.bpmData = {
        nodes:{},
        lines:{},
        listFields: []
    };
    // bpmData赋值，用于过滤无用节点
    // window.sbpmData = {
    //     nodes:{},
    //     lines:{}
    // };
    // 表单字段list
    // var listFields = [];


    /******************************** 权限start **********************/
    var app2 = new Vue({
        el:"#dataList",
        data: {
            roles: [],
            // ps: {"1118306017164132352":["delete","force_end"],"1161265834463592448":["delete"],"1165947216343334912":["force_end"],"1059767604954005504":["delete"]}
            ps:{}
        },
        methods:{
            getPs(){
                var map = {};
                this.roles.filter(e => e.ps.length)
                    .forEach(e => {
                        map[e.id] = e.ps
                    });
                return map;
            },
            setPs(roles,ps){
                this.roles = roles || [];
                if(ps){
                    this.roles.forEach(e => {
                        e.ps = ps[e.id] || [];
                    });

                }else{
                    this.roles.forEach(e => {
                        e.ps = [];
                    });
                }
            }
        }

        ,
        created(){
            var url = "/api/bpm/org/all?type=r";
            $.get(url, msg => {
                if(this.roles && this.roles.length<=0){
                    this.roles = msg.data || [];
                    this.roles.forEach(e => {
                        e.ps = this.ps[e.id] || [];
                    });
                }
            }, "json")
        }
    });
    /******************************** 权限end **********************/



    var taskNameMap = {};   // 节点名称map
    var sequenceFlowMap = {};   // 流程线map，用于指示流程的流向

    // var tmpl = template.compile($('#toolbar').html())
    // onInfront();
    function onInfront(){
        //销毁表格
        // $("#dataList").bootstrapTable("destroy");
        // $("#dataList").bootstrapTable({
        //     columns:[
        //         {checkbox: true},
        //         { field: 'text', title: "角色名称" },
        //         { title: "功能权限", formatter: function (value,row, index) {
        //                 return tmpl({
        //                     d: row
        //                 })
        //             }},
        //     ],
        //     pagination: false,
        //     sidePagination: "server",
        //     ajax: function(params){
        //
        //         params.data.id = "";
        //         var url = "/api/bpm/org/getRole";
        //         // var url = "/api/bpm/org/all?type=r";
        //         //换算分页
        //         var data = params.data;
        //         data.size = data.limit;
        //         data.page = (data.offset / data.limit) + 1;
        //         $.get(url + '?' + $.param(params.data)).then(function (res) {
        //             if(!res.success){
        //                 layer.msg("请求失败！")
        //                 return;
        //             }
        //             params.success({
        //                 rows: res.data.list,
        //                 total: res.data.totalRow,
        //             })
        //         },"json")
        //     }
        // })
    }

    function loadForm(){
        var id = $("#selectForm").val()
        layer.load(0, {time: 5000})
        $.get("/api/bpm/form/onefull", {id:id}, function (msg) {
            layer.closeAll();
            if(msg.success){
                form = msg.data;
            }
            window.fields = [];
            $.each(msg.data.form.data ||[], function (i,v) {
                fields.push(v.title)
            })
            $("#tab3").fsSelector("list", fields, bpmData.listFields)

        }, 'json')
    }

</script>

<script>

    $('#myTabs a[href="#tab1"]').tab('show');
    // var formList = [];
    var pid = getParam("pid");
    var fulldata = {
        startEvent:[],
        ext:{},
        assUser:[],
        taskList:[],
        pid: pid
    }

    // $.ajax({
    //     type:"get",
    //     url:"/api/bpm/form/queryForm",
    //     async:false,
    //     success:function(data){
    //         for (var i = 0; i < data.data.length; i++) {
    //             formList.push({"id":data.data[i]._id,"name":data.data[i].name})
    //         }
    //     }
    // });
    var catList = [];

    // 分类，表单下拉框
    var p1 = $.get("/api/bpm/form/queryForm2");
    var p2 = $.get("/api/bpm/cat/all", {type:"1"})
    $.when(p1,p2).then(function (a,b) {
        console.log(a,b);
        if ( a[0] && a[0].success) {
            // for (var i = 0; i < a[0].data.length; i++) {
            //     formList.push({"id":a[0].data[i]._id,"name":a[0].data[i].name})
            // }

            $("#formId").html(
                template("model_temp",{
                    formList:a[0].data
                })
            );
        }
        if (b[0] && b[0].success) {
            for (var i = 0; i < b[0].data.length; i++) {
                catList.push({"id":b[0].data[i]._id,"name":b[0].data[i].text})
            }

            $("#catId").html(
                template("cat_temp",{
                    catList:catList
                })
            );
        }
        setXmlData();
        loadForm()
        if(pid){
            $("#selectCat").val(pid);
        }

        importXML()
    })


    // 权限设置
    var _roles = {};
    $(document).on("click", "#setRole", function () {
        window.onChooseInit = function(){
            return _roles;
        };
        window.onChooseCallback = function(selected){
            _roles = selected;
            $("#permSet").val(Object.values(_roles).join(","))

        }
        window.open("../org/selectQ.html?type=r", "choose-user", "left=100, top=100, width=500, height=400, location=no, resizable=no")
    });

    $(document).on("click", "#cleanRole", function () {
        $("#permSet").val("");
        _roles = {};
    });


    $(document).on('change',"#selectForm",function () {
        loadForm()
    });

    var activeIndex = true;
    // 点击下一步
    $("#nextStep").click(function () {
        $('#myTabs a[href="#tab2"]').tab('show');
        // $(".li2").addClass("active");
        // $(".li1").removeClass("active");
        // $(".tab2").removeClass("hide");
        // $(".tab1").addClass("hide");
        activeIndex = false;
    })
    /*$("#myTabs li").click(function () {
        if($(this).hasClass("active")){
            return;
        }
        activeIndex = !activeIndex;
        if(activeIndex){
            $(".tab1").removeClass("hide");
            $(".tab2").addClass("hide");
            $(".tab3").removeClass("hide");
        }else{
            $(".tab2").removeClass("hide");
            $(".tab1").addClass("hide");
            $(".tab3").removeClass("hide");
        }
    });*/

    // var diagramUrl = 'https://cdn.rawgit.com/bpmn-io/bpmn-js-examples/dfceecba/starter/diagram.bpmn11';
    // modeler instance
    var bpmnModeler = new BpmnJS({
        container: '#canvas',
        keyboard: {
            bindTo: window
        }
    });

    var xml ="";
    // 加载空流程
    $.ajax({
        type:"get",
        url:"../lib/bpm/newDiagram.bpmn",
        async:false,
        success:function(data){
            console.log(data)
            xml = data;
        }
    });

    var flag = getParam("flag");
    var id = getParam("id");



    function setXmlData() {
        if(id){
            $("#check-button").show();
            $.ajax({
                type:"get",
                url: "/api/bpm/BpmXmlController/one?_id="+id,
                async:false,
                success:function(obj){
                    if(!obj.success){
                        layer.msg(obj.errMessage)
                        return;
                    }
                    $("#selectForm").val(obj.data.formId);
                    $("#selectCat").val(obj.data.pid);

                    // Vue.set(app2, "ps", JSON.parse(JSON.stringify(obj.data.permissionSet)))
                    app2.setPs(obj.data.roles,obj.data.permissionSet);

                    // obj.data
                    // if(obj["data"].length>0){
                    var bpmXml = obj.data.xml;
                    if(null != bpmXml && "" != bpmXml){
                        xml = bpmXml;

                        /*var userSourceData = {};
                        $.ajax({
                            type:"get",
                            url: remoteOrigin + "/api/auto/user/getList?page=1&size=2000",
                            async:false,
                            success:function(obj){
                                var d1 = obj.data.list;
                                d1.forEach(function (da) {
                                    userSourceData[da.id] = da.trueName;
                                })
                            }
                        })*/

                        $("#modelName").val(obj.data.modelName);
                        $("#desc").val(obj.data.desc);
                        // var pers = obj.data.permissionSet;
                        // if(pers){
                        //     $("#permSet").val(Object.values(pers).join(","));
                        //     _roles = pers;
                        // }

                        for(var i in obj.data.bpmData){
                            window.bpmData[i] = obj.data.bpmData[i];
                        }

                        if(obj.data.bpmData.elseSetting){
                            Vue.set(tab5, "data", obj.data.bpmData.elseSetting);
                        }
                        if(obj.data.trigger){
                            Vue.set(tab6, "data", obj.data.trigger);
                        }
                        // window.bpmData = obj.data.bpmData;
                        // for (var nodeId in bpmData.nodes) {
                        //     bpmData.nodes[nodeId].timeoutSet = bpmData.nodes[nodeId].timeoutSet || {
                        //         timeout:"0",
                        //         maxTimeout:"0"
                        //     }
                        // }
                        // listFields = obj.data.arrangementData.listFields;

                    }

                    // }
                }
            });
        }
    }



    var roleData = [];
    // 角色
    function getRole(){
        $.ajax({
            url: "/api/auto/org/getList?role=1&page=1&size=1000",
            type: 'GET',
            contentType: false,
            success:function (res) {
                if(res.success && res.data){
                    roleData = res.data.list;
                }
            }
        });
    }
    getRole();

    function importXML(){
        bpmnModeler.importXML(xml, function(err) {
            if (err) {
                console.log('error rendering', err);
            } else {
                console.log('rendered');
            }
        });
    }


    /**
     * Save diagram contents and print them to the console.
     */
    function exportDiagram() {

        bpmnModeler.saveXML({ format: true }, function(err, xml) {
            if (err) {
                return console.error('could not save BPMN 2.0 diagram', err);
            }
            var html = $(xml);
            var process = html.find("process").eq(0);
            //收录节点
            var existIds = {};
            var startCount = 0;
            var endCount = 0;
            var modelName = $("#modelName").val();
            var formId = $("#selectForm").val();
            var desc = $("#desc").val();
            // 分类ID
            var catId = $("#selectCat").val();
            pid = catId;
            // var mField = true;

            bpmData.workflowName = modelName;
            bpmData.formId = formId;
            process.find("task,exclusiveGateway,startEvent,endEvent").each(function(){
                var t = $(this);
                var id = t.attr("id");
                var name = t.attr("name");
                if(!bpmData.nodes[id]){
                    bpmData.nodes[id] = getNodeEmptyData();
                }
                bpmData.nodes[id].name = name;
                bpmData.nodes[id].id = id;
                bpmData.nodes[id].nextNodes = [];
                existIds[id] = 1;
                bpmData.nodes[id].type = (function () {
                    // console.log(t[0].tagName)
                   switch (t[0].tagName) {
                       case "STARTEVENT":
                           startCount++;
                           // bpmData.start = id;
                           return "start";
                       case "ENDEVENT":
                           endCount++;
                           // bpmData.end = id;
                           return "end";
                       case "TASK":
                           return "task";
                       case "EXCLUSIVEGATEWAY":
                           return "soft";
                   }
                })();

            });
            //删除没再用的节点
            var willDeleted = Object.keys(bpmData.nodes).filter(e => !existIds[e]);
            willDeleted.forEach(e => delete bpmData.nodes[e]);

            //收录线
            process.find("sequenceFlow").each(function () {
                var t = $(this);
                var id = t.attr('id');
                var name = t.attr('name');
                var _from = t.attr("sourceRef");
                var _to = t.attr("targetRef");
                //找不到节点就不管了
                var fromNode = bpmData.nodes[_from];
                var toNode = bpmData.nodes[_to];
                if(!fromNode || !toNode){
                    return
                }

                // bpmData.nodeId = id;

                //已经有配置条件
                var expression = "";
                if(bpmData.lines[id]){
                    //表达式转换
                    // expression =
                    expression = expFn(bpmData.lines[id]);
                }

                fromNode.nextNodes.push({
                    node: _to,
                    expression: expression
                })


                // var allFields = bpmData.nodes[_from].fields.allFields;
                // var requiredFields = bpmData.nodes[_from].fields.requiredFields;

                // for(var item=0;item<requiredFields.length;item++){
                //     var i = $.inArray(requiredFields[item],allFields);
                //     if("-1" == i){
                //
                //         mField = false;
                //         return false;
                //     }
                // }
            });

            //检查是否可以保存
            if(startCount > 1){
                layer.msg("开始节点有且只能存在一个！");
                return;
            }
            // if(!mField){
            //     layer.msg("必填字段必须在填写字段中存在！")
            //     return;
            // }
            // if(endCount > 1){
            //     layer.msg("结束节点有且只能存在一个！");
            //     return;
            // }


            var da = {
                _id:id,
                xml:xml,
                desc:desc,
                permissionSet:app2.getPs(), // 权限设置
                pid:pid,
                modelName:modelName,
                bpmData:bpmData,
            }
            if("" == modelName.trim()){
                layer.msg("工作流名称不能为空！");
                return;
            }

            var _data = JSON.parse(JSON.stringify(da));
            _data.bpmData.elseSetting = tab5.data;
            _data.trigger = tab6.data;

            $.ajax({
                // url:"/api/bpm/workflow/saveWorkFlow",
                url:"/api/bpm/BpmXmlController/saveBPMXML",
                type:"post",
                data: JSON.stringify(_data),
                headers:{
                    "Content-Type": "application/json"
                },
                dataType: "json",
                success:function(res){
                    if(res.success){
                        layer.msg("保存成功！")

                        if(!id){
                            location.href="../../bpm/workFlow/xml.html?flag=1&&id="+res.data;
                        }

                        // layer.alert("保存成功！", { icon: 1, closeBtn: 0 }, function () {
                        //     closeCurrentIframe();
                        // } );
                    }else{
                        layer.alert("保存失败！"+res.errMessage, { icon: 2, closeBtn: 0 }, function () {
                            layer.closeAll();
                        } )
                    }
                }
            });



            /*return;
            var _xml = $.parseXML(xml);
            var _eventMap = {};
            var _xmlMap = {};   // 最终整理的数据
            var startEvent;
            var endEvent;
            var ex =[];
            var exList ={};

            var startNum = 0;
            var endNum = 0;
            var errFlag = false;
            // var isInArr = {};
            var isInArr=false;
            $(_xml).find('process').each(function(){
                var _sequenceFlow = $(this).children('sequenceFlow');
                _sequenceFlow.each(function () {
                    var id = $(this).attr("id");
                    var targetRef = $(this).attr("targetRef");
                    sequenceFlowMap[id] = targetRef;
                })

                var _startEvent = $(this).children('startEvent');
                var _task = $(this).children('task,exclusiveGateway');
                var _endEvent = $(this).children('endEvent');
                // if(_startEvent.length>1){
                    startNum = _startEvent.length;
                // }
                // if(_endEvent.length>1){
                    endNum = _endEvent.length;
                // }
                var _startId = _startEvent.attr("id");
                startEvent = _startEvent.attr("id");
                endEvent = _endEvent.attr("id");
                var _startName = _startEvent.attr("name");
                taskNameMap[_startId] = _startName;
                var _endId = _endEvent.attr("id");
                var _endName = _endEvent.attr("name");
                taskNameMap[_endId] = _endName;
                // bpmData.nodes[_startId] = bpmData.nodes[_startId] || []
                // bpmData.nodes[_endId] = bpmData.nodes[_endId] || []
                initVar(_startId);
                initVar(_endId);


                _task.each(function () {
                    var _taskId = $(this).attr("id");
                    var _taskName = $(this).attr("name");
                    taskNameMap[_taskId] = _taskName;

                    // bpmData.nodes[_taskId] = bpmData.nodes[_taskId] || []
                    initVar(_taskId);
                    var _outgoing = $(this).children('outgoing');
                    // for (let i = 0; i < _outgoing.length; i++) {
                    //     var ss = _outgoing.eq(i);
                    // }
                    _outgoing.each(function () {
                        var targetRef = sequenceFlowMap[$(this).text()];
                        try {
                            _eventMap = arrData(_taskId, targetRef, _eventMap, $(this).text());
                        }catch (e) {
                            isInArr=e;
                        }
return
                    })

                    if(_outgoing.length == 0){
                        try {
                            _eventMap = arrData(_taskId, "", _eventMap);
                        }catch (e) {
                            isInArr = e;
                        }
                    }
                })*/


                // var _sequenceFlow = $(this).children('sequenceFlow');
                // _sequenceFlow.each(function () {
                //
                //     var nextEvent = [];
                //     var node = {};
                //     var id = $(this).attr("id");
                //     var targetRef = $(this).attr("targetRef");
                //     sequenceFlowMap[id] = targetRef;
                //
                //     // var nextNodes = {"nextEvent":nextEvent}
                //     var sourceRef = $(this).attr("sourceRef");
                //     var sr = sourceRef.split("_");
                //     var tr = targetRef.split("_");
                //     // if(sr.length>0 && "StartEvent" == sr[0]){
                //     //     startEvent = sourceRef;
                //     //     startNum++;
                //     // }
                //     // if(tr.length>0 && "EndEvent" == tr[0]){
                //     //     endEvent = targetRef;
                //     //     endNum++;
                //     // }
                //
                //     var allFields =[];
                //     var requiredFields = [];
                //     var pids = [];
                //     var qids = [];
                //     var rids = [];
                //     var dids = [];
                //     var timeout = "";
                //     var maxTimeout = "";
                //     var taskName = "";
                //     if(undefined ==  window.bpmData.nodes[sourceRef]){
                //         /*errFlag = true;
                //         layer.msg("请配置节点信息！");
                //         return;*/
                //     }else{
                //         allFields = window.bpmData.nodes[sourceRef].fields.all_fields;
                //         requiredFields = window.bpmData.nodes[sourceRef].fields.required_fields;
                //         // 可以处理的人的ID
                //         pids = arrToStr(window.bpmData.nodes[sourceRef].permission.pids);
                //         // 可以处理的组织架构ID
                //         qids =arrToStr(window.bpmData.nodes[sourceRef].permission.qids);
                //         rids =arrToStr(window.bpmData.nodes[sourceRef].permission.rids);
                //         dids =arrToStr(window.bpmData.nodes[sourceRef].permission.dids);
                //
                //         timeout = window.bpmData.nodes[sourceRef].timeoutSet.timeout;
                //         maxTimeout = window.bpmData.nodes[sourceRef].timeoutSet.maxTimeout;
                //         taskName = taskNameMap[sourceRef];
                //         var timeoutSet = {};
                //         timeoutSet["timeout"] = timeout;
                //         timeoutSet["maxTimeout"] = maxTimeout;
                //         var conList;
                //         if(undefined !=  window.bpmData.nodes[targetRef]){
                //             conList = window.bpmData.nodes[targetRef].condition;
                //         }
                //
                //         // _expression = "";
                //         // if(conList){
                //         //     $.each(conList,function (e) {
                //         //         var c = conList[e];
                //         //         preorder(c,false)
                //         //     })
                //         // }
                //         var _expression = preorderZheng(conList,"and");
                //
                //         node["node"] = targetRef;
                //         node["expression"] = _expression;
                //         nextEvent.push(node)
                //         var nextNodes = (_eventMap[sourceRef] && _eventMap[sourceRef].nextNodes) ? _eventMap[sourceRef].nextNodes : [];
                //         nextNodes.push(node);
                //     }
                //
                //     // var nodeExt =[];    // 节点对应的表单属性
                //     // nodeExt.push(window.bpmData.nodes[sourceRef].fields.all_fields);
                //
                //     if(sr.length>0 && "ExclusiveGateway" == sr[0]){
                //         ex.push({sourceRef,targetRef});
                //         exList[sourceRef] = ex;
                //     }else{
                //         _eventMap[sourceRef] = {"id":sourceRef,"name":taskName,"allFields":allFields,"requiredFields":requiredFields,"uids":pids,"qids":qids,"rids":rids,"dids":dids,"nextNodes":nextNodes,"timeoutSet":timeoutSet}
                //     }
                //
                //     window.sbpmData.nodes[sourceRef] = (window.bpmData.nodes[sourceRef]);
                // })
            // });

            /*// 网关节点
            $.each(exList, function(i) {
                var nextEvent = [];
                var node = {};

                var allFields =[];
                var requiredFields = [];
                var pids = [];
                var qids = [];
                var rids = [];
                var dids = [];
                var conList;
                var taskName = "";


                if(undefined ==  window.bpmData.nodes[sourceRef]){
                }else{
                    allFields = window.bpmData.nodes[sourceRef].fields.all_fields;
                    requiredFields = window.bpmData.nodes[sourceRef].fields.required_fields;

                    // 可以处理的人的ID
                    pids = arrToStr(window.bpmData.nodes[sourceRef].permission.pids);
                    // 可以处理的组织架构ID
                    qids =arrToStr(window.bpmData.nodes[sourceRef].permission.qids);
                    rids =arrToStr(window.bpmData.nodes[sourceRef].permission.rids);
                    dids =arrToStr(window.bpmData.nodes[sourceRef].permission.dids);
                    taskName = taskNameMap[sourceRef];
                }
                for(var ex=0;ex<exList[i].length;ex++){
                    var targetRef = exList[i][ex].targetRef;
                    conList = window.bpmData.nodes[targetRef].condition;

                    var _expression = preorderZheng(conList,"and");
                    node["expression"] = _expression;
                    node["node"] = targetRef;
                    nextEvent.push(node)
                }
                var nextNodes = [];
                nextNodes.push(node);
                _eventMap[exList[i].sourceRef] = {"id":exList[i],"name":taskName,"allFields":allFields,"requiredFields":requiredFields,"uids":pids,"qids":qids,"rids":rids,"dids":dids,"nextNodes":nextNodes}
            });

            // 开始节点
            $(_xml).find('startEvent').each(function(){
                // 节点流向ID
                var _outgoing = $(this).children('outgoing');
                var _taskId = $(this).attr("id");
                _outgoing.each(function () {
                    var targetRef = sequenceFlowMap[$(this).text()];
                    try {
                        _eventMap = arrData(_taskId, targetRef, _eventMap, $(this).text());
                    }catch (e) {
                        isInArr = e;
                    }
                })
            })

            // 结束节点
            $(_xml).find('endEvent').each(function(){
                var sourceRef = $(this).attr("id");
                var allFields =[];
                var requiredFields = [];
                var pids = [];
                var qids = [];
                var rids = [];
                var dids = [];
                var taskName = "";
                var filterRule = "";
                var chooseRule = "";
                var targetRule = "";
                // var nextNodes = [];
                // var node = {};
                if(undefined ==  window.bpmData.nodes[sourceRef]){
                }else{
                    if(window.bpmData.nodes[sourceRef].permission){

                        // allFields = window.bpmData.nodes[sourceRef].fields.all_fields;
                        // requiredFields = window.bpmData.nodes[sourceRef].fields.required_fields;
                        // 可以处理的人的ID
                        pids = arrToStr(window.bpmData.nodes[sourceRef].permission.pids);
                        // 可以处理的组织架构ID
                        qids =arrToStr(window.bpmData.nodes[sourceRef].permission.qids);
                        rids =arrToStr(window.bpmData.nodes[sourceRef].permission.rids);
                        dids =arrToStr(window.bpmData.nodes[sourceRef].permission.dids);
                        if(window.bpmData.nodes[sourceRef].intelligence ){
                        }else{
                            window.bpmData.nodes[sourceRef].intelligence = {     filterRule:"all",
                                chooseRule:"none",
                                targetRule: ""};
                        }
                        var intelligen;
                        if(window.bpmData.nodes[sourceRef].intelligence){
                            intelligen =window.bpmData.nodes[sourceRef].intelligence;
                            filterRule = intelligen.filterRule;
                            chooseRule = intelligen.chooseRule;
                            targetRule = intelligen.targetRule;
                        }
                        taskName = taskNameMap[sourceRef];
                        // var conList = window.bpmData.nodes[sourceRef].condition;
                        // var _expression = preorderZheng(conList,"and");
                        //
                        // node["expression"] = _expression;
                        // nextNodes.push(node);
                    }
                }
                _eventMap[sourceRef] = {"id":sourceRef,"name":taskName,"allFields":allFields,"requiredFields":requiredFields,"uids":pids,"qids":qids,"rids":rids,"dids":dids,"nextNodes":[],"filterRule":filterRule,"chooseRule":chooseRule,"targetRule":targetRule}
                window.sbpmData.nodes[sourceRef] = (window.bpmData.nodes[sourceRef]);
                // window.sbpmData.lines[sourceRef] = (window.bpmData.lines[sourceRef]);
            })

            if(!errFlag){
                if(isInArr){
                    layer.msg("必填字段必须在填写字段中存在！")
                    return;
                }
                if(startNum == 0 || endNum == 0 || startNum>1 || endNum>1){
                    layer.msg("开始或结束节点有且只能存在一个！");
                    return;
                }

                // var _formDataMap = {}
                var formId = $("#selectForm").val();
                var modelName = $("#modelName").val();
                if("" == modelName.trim()){
                    layer.msg("工作流名称不能为空！");
                    return;
                }
                // $.ajax({
                //     type:"get",
                //     async:false,
                //     url:"/api/bpm/form/queryFormData?_id="+formId,
                //     success:function(res){
                //         if(res.code==200&& res.data.length>0){
                //             var data = res.data[0].form.data;
                //             data.forEach(function (e) {
                //                 _formDataMap[e.title] = e;
                //             })
                //         }
                //     }
                // });
                // _xmlMap = {"formId":formId,"template":"","rendered":"","workflowName":modelName,"fields":null,"nodes":_eventMap,"start":startEvent,"end":endEvent,"listFields":listFields}

                var da = {
                    _id:id,
                    xml:xml,
                    pid:pid,
                    modelName:modelName,
                    // data:fulldata,
                    bpmData:sbpmData,
                    // arrangementData:_xmlMap
                }

                $.ajax({
                    // url:"/api/bpm/workflow/saveWorkFlow",
                    url:"/api/bpm/BpmXmlController/saveBPMXML",
                    type:"post",
                    data: JSON.stringify(da),
                    headers:{
                        "Content-Type": "application/json"
                    },
                    dataType: "json",
                    success:function(res){
                        if(res.success){
                            layer.msg("保存成功！")
                            // layer.alert("保存成功！", { icon: 1, closeBtn: 0 }, function () {
                            //     closeCurrentIframe();
                            // } );
                        }else{
                            layer.alert("保存失败！"+res.errMessage, { icon: 2, closeBtn: 0 }, function () {
                                layer.closeAll();
                            } )
                        }
                    }
                });
            }*/

            /*$.ajax({
                url: "/api/bpm/BpmXmlController/saveBPMXML?xml="+xml+"&&data="+JSON.stringify(fulldata)+"&&_id="+id+"&&modelName="+modelName+"&&pid="+pid+"&bpmData="+JSON.stringify(window.bpmData),
                success: function (res) {
                    console.log("res",res)
                    if(!res.data || code != 200){
                        layer.msg(res.errMessage);
                    }
                }
            });*/
        });
    }
    /**
     * Open diagram in our modeler instance.
     *
     * @param {String} bpmnXML diagram to display
     */
    function openDiagram(bpmnXML) {
        // import diagram
        bpmnModeler.importXML(bpmnXML, function(err) {
            if (err) {
                return console.error('could not import BPMN 2.0 diagram', err);
            }
            // access modeler components
            var canvas = bpmnModeler.get('canvas');
            var overlays = bpmnModeler.get('overlays');
            // zoom to fit full viewport
            canvas.zoom('fit-viewport');
            // attach an overlay to a node
            overlays.add('SCAN_OK', 'note', {
                position: {
                    bottom: 0,
                    right: 0
                },
                html: '<div class="diagram-note">Mixed up the labels?</div>'
            });
            // add marker
            canvas.addMarker('SCAN_OK', 'needs-discussion');
        });
    }
    // load external diagram file via AJAX and open it
    // $.get(diagramUrl, openDiagram, 'text');
    // wire save button
    $('#save-button').click(exportDiagram);
    $('#check-button').click(function () {
        layer.load(2, {time: 5000});
        $.get("/api/bpm/workflow/check", {id:id}, function (msg) {
            layer.closeAll();
            if(!msg.success){
                layer.msg(msg.errMessage);
            }

            var err = (msg.data || []).join("<br>");
            if(err){
                layer.open({
                    title:"错误明细",
                    content: err
                })                ;
            } else {
                layer.msg("检查完毕，暂无错误");
            }
        },"json")
    });

    // loadForm()

    // 获取选中的表单值
    // function formInfoData() {
    //     var form = $("#selectForm").val();
    //     $.ajax({
    //         type:"get",
    //         url:"/api/bpm/form/queryFormData?_id="+form,
    //         success:function(res){
    //             var _formDataMap = {}
    //             if(res.code==200&& res.data.length>0){
    //                 var data = res.data[0].form.data;
    //
    //                 data.forEach(function (e) {
    //                     _formDataMap[e.title] = e;
    //                 })
    //                 console.log("sss",_formDataMap)
    //             }
    //             return _formDataMap;
    //         }
    //     });
    // }

    // 数组转字符串
    function arrToStr(arr) {
        var ret = []
        $.each(arr ||[], function (i,v) {
            ret.push(v+"")
        });
        return ret
    }

    // 节点配置回调事件
    // function bd(e,obj) {
    //     // 当前选中节点id
    //     fulldata.taskId=obj.id;
    //     var modelName = $("#modelName").val();
    //     var form = $("#selectForm").val();
    //     // bpmData.nodes[obj.id].name = obj.name;
    //
    //     bpmData.nodes[obj.id] = bpmData.nodes[obj.id] || {
    //         fields:{
    //             all_fields: [],
    //             required_fields:[],
    //         },
    //         permission:{
    //             //中文
    //             ps: [],
    //             qs: [],
    //             ds: [],
    //             rs: [],
    //             //id
    //             pids:[],
    //             qids:[],
    //             dids:[],
    //             rids:[]
    //         },
    //         condition: [],
    //         timeoutSet:{
    //             timeout:"0",
    //             maxTimeout:"0",
    //         },
    //         // allowUpload:false,
    //         quanxian:[]
    //     };
    //     window.open("./node.edit.html?id=" + obj.id,"node_edit_" + obj.id, "left=200, top=100, width=800, height=500, location=no")
    //
    // }

    // var _expression = "";
    // var exp = "";

    // 节点设置中转入条件值处理
    function preorderZheng(item,type) {
        if(!item || !item.length){
            return;
        }
        var arr = [];
        $.each(item, function (i,v) {
            //A 等于 B
            //calculate('A', '等于', 'B')
            // getValue('市场部同意与否')=='同意'
            arr.push("calculate('"+v.field+"'," + "'"+v.op+"',"+ "'"+v.value+"')")
            // arr.push("getValue('"+v.field+"')" + conversion(v.op)+ "'"+v.value+"'")

               // if(v.type == 'rule'){
               //     arr.push(conversion(v.text).replace(/\[(.+?)\]/g, "getValue('$1')"));
               // } else if(v.type == 'group'){
               //     arr.push(preorderZheng(v.children,v.text));
               // }

            // ((getValue('市场部同意与否') == '不同意' || getValue('审查岗同意与否') == '不同意' || getValue('风险部同意与否') == '同意' || getValue('风险部同意与否') == '不同意'))
        });
        arr = arr.filter(function (e) {
            return e
        });
        return "(" + arr.join(" && ") + ")";
        // switch (type.toUpperCase()) {
        //     case "AND":
        //         return "(" + arr.join(" && ") + ")";
        //
        //     case "OR":
        //         return "(" + arr.join(" || ") + ")";
        // }
    }

    // 流程节点数据整理
    // function arrData(_taskId,targetRef, _eventMap, sequenceFlowId) {
    //     var nextEvent = [];
    //     var node = {};
    //
    //     var allFields =[];
    //     var requiredFields = [];
    //     var pids = [];
    //     var qids = [];
    //     var rids = [];
    //     var dids = [];
    //     var timeout = "";
    //     var maxTimeout = "";
    //     var taskName = "";
    //     var isInArr = 0;    // 用于判断节点必填字段是否在填写字段中
    //     var expression = "";// 条件表达式
    //     var filterRule = "";
    //     var chooseRule = "";
    //     var targetRule = "";
    //     if(undefined ==  window.bpmData.nodes[_taskId]){
    //
    //     }else{
    //         if(window.bpmData.nodes[_taskId].fields){
    //
    //             allFields = window.bpmData.nodes[_taskId].fields.all_fields;
    //             requiredFields = window.bpmData.nodes[_taskId].fields.required_fields;
    //             requiredFields.forEach(function (item) {
    //                 var i = $.inArray(item,allFields);
    //                 if("-1" == i){
    //                     isInArr = i;
    //                 }
    //             })
    //
    //             // 可以处理的人的ID
    //             pids = arrToStr(window.bpmData.nodes[_taskId].permission.pids);
    //             // 可以处理的组织架构ID
    //             qids =arrToStr(window.bpmData.nodes[_taskId].permission.qids);
    //             rids =arrToStr(window.bpmData.nodes[_taskId].permission.rids);
    //             dids =arrToStr(window.bpmData.nodes[_taskId].permission.dids);
    //
    //             if(window.bpmData.nodes[_taskId].intelligence ){
    //             }else{
    //                 window.bpmData.nodes[_taskId].intelligence = {          filterRule:"all",
    //                     chooseRule:"none",
    //                     targetRule: ""
    //                 };
    //             }
    //             var intelligen;
    //             if(window.bpmData.nodes[_taskId].intelligence){
    //                 intelligen =window.bpmData.nodes[_taskId].intelligence;
    //                 filterRule = intelligen.filterRule;
    //                 chooseRule = intelligen.chooseRule;
    //                 targetRule = intelligen.targetRule;
    //                 // intelligen = JSON.parse(window.bpmData.nodes[_taskId].intelligence);
    //             }
    //             // var s = {"filterRule":"all","chooseRule":"none","targetRule":"Task_1rtduak"};
    //             // for(var item in intelligen){
    //             //     console.log("------",intelligen[item])
    //             // }
    //
    //
    //             var arr = window.bpmData.nodes[_taskId].quanxian || [];
    //
    //             var allowUpload = arr.indexOf("allowUpload") > -1;
    //             var allowDownload = arr.indexOf("allowDownload") > -1;
    //             var allowBack = arr.indexOf("allowBack") > -1;
    //             var departmentFirst = arr.indexOf("departmentFirst") > -1;
    //
    //             timeout = window.bpmData.nodes[_taskId].timeoutSet.timeout;
    //             maxTimeout = window.bpmData.nodes[_taskId].timeoutSet.maxTimeout;
    //             taskName = taskNameMap[_taskId];
    //             var timeoutSet = {};
    //
    //
    //             timeoutSet["timeout"] = timeout;
    //             timeoutSet["maxTimeout"] = maxTimeout;
    //             var conList;
    //             if(undefined !=  window.bpmData.nodes[targetRef]){
    //                 conList = window.bpmData.nodes[targetRef].condition;
    //             }
    //             if(undefined != window.bpmData.lines){
    //                 if(undefined != window.bpmData.lines[sequenceFlowId]){
    //                     conList = window.bpmData.lines[sequenceFlowId].conditions;
    //                     var expre = window.bpmData.lines[sequenceFlowId].expression;
    //                     expre = (expre || "").replace(/and/gi, " && ").replace(/or/gi, " || ");
    //                     if("" == expre.trim()){
    //                         expression = preorderZheng(conList,"and",expre);
    //                         console.log("---",expression)
    //                     }else{
    //                         var arr = {};
    //                         var reg = /\d+/g;
    //                         var ms = expre.replace(/\[(.+?)\]/g, "$1").match(reg)
    //                         for(var m=0;m<ms.length;m++){
    //                             if(undefined != conList[ms[m]-1]){
    //                                 arr[ms[m]] =("getValue('"+conList[ms[m]-1].field+"')" + conversion(conList[ms[m]-1].op)+ "'"+conList[ms[m]-1].value+"'")
    //
    //                             }
    //                         }
    //
    //                         // [3] and [1] and [4]
    //                         for(var s=0;s<ms.length;s++){
    //
    //                             if(undefined != arr[ms[s]]){
    //                                 expre = expre.replace("["+ms[s]+"]",arr[ms[s]]);
    //                             }
    //                         }
    //                         expression = "("+expre+")";
    //                         console.log("----",expression)
    //                     }
    //
    //                 }
    //             }
    //             // var _expression = preorderZheng(conList,"and");
    //
    //         }
    //             node["node"] = targetRef;
    //             node["expression"] = expression;
    //             nextEvent.push(node)
    //             var nextNodes = (_eventMap[_taskId] && _eventMap[_taskId].nextNodes) ? _eventMap[_taskId].nextNodes : [];
    //             nextNodes.push(node);
    //     }
    //
    //     var sr = _taskId.split("_");
    //     if(sr.length>0 && "ExclusiveGateway777777777" == sr[0]){
    //         ex.push({_taskId,targetRef});
    //         exList[_taskId] = ex;
    //     }else{
    //         _eventMap[_taskId] = {"id":_taskId,"name":taskName,"allFields":allFields,"requiredFields":requiredFields,"uids":pids,"qids":qids,"rids":rids,"dids":dids,"nextNodes":nextNodes,"timeoutSet":timeoutSet,"allowUpload":allowUpload,"allowDownload":allowDownload,"allowBack":allowBack,"departmentFirst":departmentFirst,"filterRule":filterRule,"chooseRule":chooseRule,"targetRule":targetRule}
    //     }
    //
    //     window.sbpmData.nodes[_taskId] = (window.bpmData.nodes[_taskId]);
    //     if(window.bpmData.lines){
    //         window.sbpmData.lines[sequenceFlowId] = (window.bpmData.lines[sequenceFlowId]);
    //     }
    //     if(isInArr == "-1"){
    //         // isIn["flag"] = true;
    //         throw true;
    //         // return;
    //     }
    //     return _eventMap;
    // }

    // function preorder(root,flag) {
    //     var text = root.text;
    //     if (!root) {
    //         return;
    //     }
    //     if(root.type=="rule" ){
    //         return conversion(text).replace(/\[(.+?)\]/g, "getValue('$1')")
    //
    //         // var textSub = text.substr(1,text.lastIndexOf("]")-1);
    //         // var textLe = text.substr(text.lastIndexOf("]")+1,text.length);
    //         // if(flag){
    //         //     _expression = _expression+exp +" "+'getValue("'+textSub+'")'+textLe+" ";
    //         // }else{
    //         //     _expression = _expression+'getValue("'+textSub+'")'+textLe +" ";
    //         // }
    //     }else if(root.type=="group"){
    //         var children = root.children;
    //         var arr = [];
    //         $.each(children, function (i) {
    //             var str = preorder(children[i],true);
    //             if(str){
    //                 arr.push(str);
    //             }
    //         });
    //         if(!arr.length){
    //             return "";
    //         }
    //         if(("AND" == text.toUpperCase())){
    //             return "(" + arr.join("&&") + ")";
    //         }
    //         if( "OR" == text.toUpperCase()){
    //             return "(" + arr.join("||") + ")";
    //             // exp = text.toUpperCase();
    //             // if("AND" == exp){
    //             //     exp = "&&";
    //             // }else if("OR" == exp){
    //             //     exp = "||"
    //             // }
    //             // _expression = _expression+root.text + " ";
    //         }
    //     }
    // }

    function expFn(lineId) {
        var expression = "";
        var conList;
        if(undefined != lineId){
            conList = lineId.conditions;
            var expre = lineId.expression;
            expre = (expre || "").replace(/and/gi, " && ").replace(/or/gi, " || ");
            if("" == expre.trim()){
                expression = preorderZheng(conList,"and",expre);
            }else{
                var arr = {};
                var reg = /\d+/g;
                var ms = expre.replace(/\[(.+?)\]/g, "$1").match(reg)
                for(var m=0;m<ms.length;m++){
                    if(undefined != conList[ms[m]-1]){
                        arr[ms[m]] =("calculate('"+conList[ms[m]-1].field+"'," + "'"+conList[ms[m]-1].op+"',"+ "'"+conList[ms[m]-1].value+"')")

                    }
                }

                for(var s=0;s<ms.length;s++){
                    if(undefined != arr[ms[s]]){
                        expre = expre.replace("["+ms[s]+"]",arr[ms[s]]);
                    }
                }
                expression = "("+expre+")";
            }
        }
        return expression;
    }

    function conversion(str) {
        return (str || "")
            .replace(/大于等于/g, ">=")
            .replace(/小于等于/g, "<=")
            .replace(/大于/g, ">")
            .replace(/小于/g, "<")
            .replace(/不等于/g, "!=")
            .replace(/等于/g, "==")
            .replace(/“|”/g, "\"")
            .replace(/‘|’/g, "'");
        // return str ? str.replace(/(大于|小于|大于等于|小于等于|等于')/g, (a) => {
        //     return {
        //         '小于': '<',
        //         '大于等于': '>=',
        //         '小于等于': '<=',
        //         '大于': '>',
        //         '等于': '=',
        //     }[a]
        // }) : '';
        // if(-1 != str.indexOf("大于")){
        //     str = str.replace("大于",">");
        // }
        // if(-1 != str.indexOf("小于")){
        //     str = str.replace("小于","<");
        // }
        // if(-1 != str.indexOf("大于等于")){
        //     str = str.replace("大于等于",">=");
        // }
        // if(-1 != str.indexOf("小于等于")){
        //     str = str.replace("小于等于","<=");
        // }
        // if(-1 != str.indexOf("等于")){
        //     str = str.replace("等于","==");
        // }
        // return str;
    }
    
    // function initVar(id) {
    //     bpmData.nodes[id] = bpmData.nodes[id] || {
    //         fields:{
    //             all_fields: [],
    //             required_fields:[],
    //         },
    //         permission:{
    //             //中文
    //             ps: [],
    //             qs: [],
    //             ds: [],
    //             rs: [],
    //             //id
    //             pids:[],
    //             qids:[],
    //             dids:[],
    //             rids:[]
    //         },
    //         condition: [],
    //         timeoutSet:{
    //             timeout:"0",
    //             maxTimeout:"0",
    //         },
    //         // allowUpload:false,
    //         quanxian:[],
    //         intelligence:{
    //             filterRule:"all",
    //             chooseRule:"none",
    //             targetRule: ""
    //         }
    //         // filterRule:"",
    //         // chooseRule:"",
    //         // targetRule:""
    //     };
    // }


</script>

</body>
</html>


<script>
    function openConfigPage(id,page){
        window.open("./node.edit.html?id=" + id + "&page=" + page ,"node_edit_" + id, "left=200, top=100, width=1000, height=500, location=no")
    }

    //图形配置
    $.contextMenu({
        // define which elements trigger this menu
        selector: ".djs-element.djs-shape[data-element-id]",
        // define the elements of the menu
        items: {
            m1: {name: "处理人", icon: "fa-user-o", callback: function(key, opt){
                var id = $(this).attr("data-element-id");
                openConfigPage(id, "dealers")
            }},
            m6: {
                name:"智能选人", icon: "fa-filter",callback: function () {
                    var id = $(this).attr("data-element-id");
                    openConfigPage(id, "smart")
                }
            },
            m7:{
                name:"流转设置",
                icon:"fa-stack-overflow",
                callback: function () {
                    var id = $(this).attr("data-element-id");
                    openConfigPage(id, "flow")
                }
            },

            m2: {name: "填写字段", icon:"fa-pencil-square-o", callback: function(key, opt){
                var id = $(this).attr("data-element-id");
                openConfigPage(id, "fields");
            }},
            m3: {name: "必填字段", icon:"fa-pencil-square-o", callback: function(key, opt){
                var id = $(this).attr("data-element-id");
                openConfigPage(id, "rfields");
            }},
            m10:{
                name:"数据源",
                icon:"fa-database",
                callback: function () {
                    var id = $(this).attr("data-element-id");
                    openConfigPage(id, "datasource");
                }
            },
            m5: {
                name: "权限配置",
                icon: "fa-laptop",
                callback: function () {
                    var id = $(this).attr("data-element-id");
                    openConfigPage(id, "permission")
                }
            },
            m4: {name: "超时提醒", icon:"fa-bell", callback: function(key, opt){
                var id = $(this).attr("data-element-id");
                openConfigPage(id, "timeout");
            }},
            mc: {
                name:"子流程",
                icon: "fa-child",
                callback: function () {
                    var id = $(this).attr("data-element-id");
                    openConfigPage(id, "childprocess")
                }
            }
        }
        // there's more, have a look at the demos and docs...
    });

    $.contextMenu({
        selector: "[data-element-id*=SequenceFlow]",
        items:{
            m1: {
                name: "条件设置",
                icon: "fa-check-square-o",
                callback: function () {
                    var id = $(this).attr("data-element-id");
                    window.open("./lineCondition.html?id=" + id,"line_edit", "left=200, top=100, width=800, height=500, location=no")
                }
            }
        }
    })


    // 获取所有节点
    function getNode() {
        var nodeMap = {};
        bpmnModeler.saveXML({ format: false }, function(err, xml) {
            if (err) {
                return console.error('could not save BPMN 2.0 diagram', err);
            }
            var _xml = $.parseXML(xml);
            $(_xml).find('process').each(function(){
                var _startEvent = $(this).children('startEvent');
                var _task = $(this).children('task,exclusiveGateway');
                var _endEvent = $(this).children('endEvent');

                var _startId = _startEvent.attr("id");
                var _startName = _startEvent.attr("name");
                nodeMap[_startId] = _startName;

                var _endId = _endEvent.attr("id");
                var _endName = _endEvent.attr("name");
                _task.each(function () {
                    var _taskId = $(this).attr("id");
                    var _taskName = $(this).attr("name");
                    nodeMap[_taskId] = _taskName;
                })
                nodeMap[_endId] = _endName;
            })
        })
        return nodeMap;
    }


</script>
